<template>
  <div>
    <el-upload
      :disabled="disabled"
      :readonly="readonly"
      :action="uploadAction"
      :headers="headers"
      :multiple="isMultiple"
      :file-list="fileList"
      list-type="picture-card"
      :show-file-list="isMultiple"
      :on-preview="handlePreview"
      :on-remove="handleRemove"
      :on-change="handleChange">
      <img v-if="!isMultiple && picUrl" :src="getAvatarView()" style="height:100%;width:100%;" />
      <i v-else class="el-icon-plus"></i>
    </el-upload>
    <el-dialog :append-to-body="true" :visible.sync="previewVisible">
      <img width="100%" :src="previewImage" alt="">
    </el-dialog>
  </div>
</template>

<script>

  import Vue from 'vue'
  import { ACCESS_TOKEN } from "@/store/mutation-types"
  import { getFileAccessHttpUrl } from '@/api/manage'

  const uidGenerator=()=>{
    return '-'+parseInt(Math.random()*10000+1,10);
  }
  const getFileName=(path)=>{
    if(path.lastIndexOf("\\")>=0){
      let reg=new RegExp("\\\\","g");
      path = path.replace(reg,"/");
    }
    return path.substring(path.lastIndexOf("/")+1);
  }

  export default {
    name: 'ImageUpload',
    data(){
      return {
        uploadAction:window._CONFIG['domianURL']+"/sys/common/upload",
        urlView:window._CONFIG['staticDomainURL'],
        fileList: [],
        headers:{},
        previewImage:"",
        previewVisible: false,
        picUrl:false,
        path:""
      }
    },
    watch:{
      value(val){
        if (val instanceof Array) {
          val = val.join(',')
        }
        if(val !== this.path){
          this.initFileList(val)
          this.path = val;
        }
      }
    },
    created(){
      const token = Vue.ls.get(ACCESS_TOKEN);
      this.headers = {"X-Access-Token":token}
    },
    props:{
      value:{
        type:[String,Array],
        required:false,
        default: ""
      },
      isMultiple:{
        type:Boolean,
        required:false,
        default: true
      },
      disabled:{
        type:Boolean,
        required:false,
        default: false
      },
      readonly:{
        type:Boolean,
        required:false,
        default: false
      }
    },
    model: {
      prop: 'value',
      event: 'change'
    },
    methods: {
      initFileList(paths) {
        if (!paths || paths.length == 0) {
          this.fileList = [];
          return;
        }
        this.picUrl = true;
        let fileList = [];
        let arr = paths.split(",")
        for (var a = 0; a < arr.length; a++) {
          let url = getFileAccessHttpUrl(arr[a], this.urlView, "http");
          fileList.push({
            uid: uidGenerator(),
            name: getFileName(arr[a]),
            status: 'success',
            url: url,
            response: {
              status: "history",
              message: arr[a]
            }
          })
        }
        this.fileList = fileList
      },
      handleChange(file, fileList) {
        this.picUrl = false;
        if(file.status==='success'){
          if(file.response.success){
            this.picUrl = true;
          }
        }else if (file.status === 'fail') {
          this.$message.error(`${info.file.name} 上传失败.`);
        }
        if(file.status==='success'){
          this.handlePathChange(fileList)
        }
      },
      handlePathChange(fileList){
        let uploadFiles = fileList
        if(!uploadFiles || uploadFiles.length==0){
          this.path = ''
        }
        let arr = [];
        if(!this.isMultiple){
          arr.push(uploadFiles[uploadFiles.length-1].response.message)
        }else{
          for(var a=0;a<uploadFiles.length;a++){
            arr.push(uploadFiles[a].response.message)
          }
        }
        if(arr.length>0){
          this.path = arr.join(",")
        }
        console.log( this.path)
        this.$emit('change', this.path);
      },
      handleRemove(file, fileList) {
        this.handlePathChange(fileList);
      },
      // 预览
      handlePreview (file) {
        this.previewImage = file.url || file.thumbUrl
        this.previewVisible = true
        //

      },
      getAvatarView(){
        if(this.fileList.length>0){
          let url = this.fileList[this.fileList.length-1].url
          return getFileAccessHttpUrl(url,this.urlView,"http")
        }
      },
    }
  }
</script>

<style scoped>

</style>
